<template>
  <div class="info3-container">
    <h3 class="info3-container-title">实时体征</h3>
    <div class="vital-signs-grid">
      <div v-for="sign in vitalSigns" :key="sign.label" class="vital-sign-item" :style="{ backgroundColor: sign.color }">
        <div class="label">{{ sign.label }}</div>
        <div class="value">{{ sign.value }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const initialVitalSigns = [
  { label: '收缩压(mmHg)', value: 120, color: '#FFF1F2', normalRange: { min: 105, max: 135 } },
  { label: '舒张压(mmHg)', value: 80, color: '#FFF1F2', normalRange: { min: 65, max: 95 } },
  { label: '心率(次/分)', value: 78, color: '#FFF1F2', normalRange: { min: 63, max: 93 } },
  { label: '血氧(%)', value: 98, color: '#FFF1F2', normalRange: { min: 83, max: 112 } },
  { label: '呼吸(次/分)', value: 16, color: '#FFF1F2', normalRange: { min: 8, max: 25 } },
  { label: '脉搏(次/分)', value: 100, color: '#FFF1F2', normalRange: { min: 85, max: 115 } }
];

const vitalSigns = ref(JSON.parse(JSON.stringify(initialVitalSigns)));

let intervalId = null;

function updateVitalSigns() {
  const alertColor = '#f7c2c2'; // 警报色

  vitalSigns.value = initialVitalSigns.map(sign => {
    const baseValue = sign.value;
    // 生成随机数
    const randomChange = Math.floor(Math.random() * 41) - 20;
    let newValue = baseValue + randomChange;
    
    if (sign.label === '血氧(%)') {
      newValue = Math.min(100, Math.max(0, newValue));
    } else {
      newValue = Math.max(0, newValue);
    }
    //判断数值安全范围
    const isOutOfRange = newValue < sign.normalRange.min || newValue > sign.normalRange.max;

    return {
      ...sign,
      value: newValue,
      color: isOutOfRange ? alertColor : sign.color,
    };
  });
}

onMounted(() => {
  intervalId = setInterval(updateVitalSigns, 2000);
});

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId);
  }
});
</script>

<style scoped src="./LeftInfo3.css"></style>